#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<cassert>
#include<string.h>
#include<string>
int main()
{
    // 1.创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if(n < 0)
    {
        std::cout<< "pipe error, "<< errno << ": " << strerror(errno) << std::endl;
        return 1;
    }
    std::cout << "pipefd[0]:" << pipefd[0] << std::endl;
    std::cout << "pipefd[1]:" << pipefd[1] << std::endl;
    // 2.创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        exit(1);
    }
    else if(id == 0)
    {
        // 3.关闭不需要的fd，默认父进程读，子进程写
        close(pipefd[0]);  // 子进程关闭读

        // 4.开始通信 --- 根据特定场景
        char buff[1024];
        std::string name = "我是子进程";
        int cnt = 0;
        while(true)
        {
            snprintf(buff, sizeof(buff), "%s,我的pid：%d,%d\n",name.c_str(),getpid(),cnt++);
            write(pipefd[1], buff, strlen(buff));
            sleep(1);
        }

        close(pipefd[1]);
        exit(0);
    }
    close(pipefd[1]);  // 父进程关闭写

    // 4.开始通信  ---  根据特定场景
    char buff[1024];
    while(true)
    {
        int n = read(pipefd[0], buff, sizeof(buff)-1);
        if(n > 0)
        {
            buff[n] = '\0';
            std::cout << "子进程发送的消息：" << buff;
        }
    }

    close(pipefd[0]);
    return  0;
}